<?php
namespace app\admin\controller;

use app\common\model\AddressModel;
use app\common\model\GoodsOrderModel;
use app\common\model\MemberModel;
use app\common\model\RechargeModel;
use app\common\model\RewardModel;
use app\common\service\AddressService;
use app\common\service\NoticeService;
use common\util\ArrayUtil;
use common\util\Tools;
use think\Log;
use think\Request;
use web\util\WebUtil;
use app\common\service\MsgService;

class Agent extends Base {

    /*
     * 初始化操作
     */
    public function _initialize() {
        $this->needLogin();
    }

    // 代理列表
    public function index() {
        $url = Request::instance()->domain() . '/mobile/index/register.html';
        $this->assign('reg_url', $url);
        return $this->fetch();
    }

    /**
     * 列表
     */
    public function lists() {
        $length = 10;
        $start = $this->request->param('start', 0);
        $draw = $this->request->param('draw', 1);
        $title = $this->request->param('title', '');
        $grade = $this->request->param('grade', '');
        $status = $this->request->param('status', '');

        $where = [];
        if ($title) {
            $where['name|tel|weixin'] = [
                'like',
                '%' . $title . '%'
            ];
        }

        if ($grade != 0) {
            $where['grade'] = $grade;
        }

        if ($status > 0) {
            $where['status'] = $status;
        }

        $list = MemberModel::where($where)->limit($start, $length)
            ->order('id', 'desc')
            ->select();
        $count = MemberModel::where($where)->count();

        $ids = ArrayUtil::getKeyValuesFromArray($list, 'fid');
        if ($list) {
            $idMap = [];
            if ($ids) {
                $idMap = MemberModel::instance()->getItemsByIds($ids, 'name');
            }
            foreach ($list as &$item) {
                $item['fname'] = '';
                if (array_key_exists($item['fid'], $idMap)) {
                    $item['fname'] = $idMap[$item['fid']];
                }
            }
        }
        $totalCount = MemberModel::count();
        $data = array(
            "returnCode" => 1,
            "returnMsg" => "success!",
            'recordsTotal' => $totalCount,
            'recordsFiltered' => $count,
            'draw' => $draw,
            'data' => $list
        );
        return json($data);
    }

    /**
     * 查询一条记录
     */
    public function find() {
        $id = $this->request->param('id');
        $data = MemberModel::instance()->find($id);
        if ($data) {
            return $this->returnResult(1, "success!", $data);
        } else {
            return $this->returnResult(- 1, "success!", $data);
        }
    }

    /**
     * 更新手机号
     */
    public function update_tel() {
        $id = $this->request->param('id');
        $tel = $this->request->param('tel');
        if (empty($tel)) {
            return $this->returnResult(- 1, '手机号不能为空');
        }
        $member = MemberModel::instance()->where('tel', $tel)->find();
        if ($member && $id != $member) {
            return $this->returnResult(- 1, '手机号已经存在');
        }
        $data = [
            'id' => $id,
            'tel' => $tel,
            'password' => getPwd($tel)
        ];

        $res = MemberModel::instance()->update($data);
        if ($res) {
            return $this->returnResult(1, "更换成功!");
        } else {
            return $this->returnResult(-2, "更换失败!");
        }
    }

    /**
     * 后台代理审核
     */
    public function shenhe() {
        $id = $this->request->param('id');
        $status = $this->request->param('status');
        $beizhu = $this->request->param('beizhu');
        $member = MemberModel::instance()->find($id);

        if (empty($member)) {
            return $this->returnResult(- 1, '数据不存在');
        }

        
        if ($status == 1 && $member['status'] != 2) {
            return $this->returnResult(- 1, '已经审核');
        }
        
        $openid= $member['openid'];

        if ($status == 1) { // 通过
            $data = $this->request->param();
            $data['updatetime'] = Tools::getCurDate();
            $res = MemberModel::instance()->update($data);
            if ($res) {
                if($openid){
                    MsgService::sendRegSuccessMsg($openid, $member['name']);
                }
                
                $pid = $member['fid'];
                if ($pid) {
                    $pmember = MemberModel::instance()->find($pid);
                    $popenid = $pmember['openid'];
                    if($popenid){
                        MsgService::sendAgentJoinMsg($popenid, $id, date('Y.m.d H:i:s'), $member['name']);
                    }
                    //给父级发消息
                    if ($pmember['grade'] == 1) {
                        // 品正商
                        // 父级代理的一级代理个数
                        $count = MemberModel::instance()->where('status', 1)
                            ->where('fid', $pid)
                            ->count();
                        if ($count > 30) {
                            MemberModel::instance()->update([
                                'id' => $pid,
                                'grade' => 2
                            ]);
                            //
                            $popenid && MsgService::sendLevelChangeMsg($popenid, date('Y.m.d H:i:s'));
                        }
                    }
                }
                return $this->returnResult(1, '成功');
            } else {
                return $this->returnResult(- 1, '失败');
            }
        } else {
            Log::write("delete member id:$id,remark:$beizhu");
            $data = [
                'id'=>$id,
                'status'=>3,
                'beizhu'=>$beizhu,
            ];
            $res = MemberModel::instance()->update($data);
            if ($res) {
                
                
                $pid = $member['fid'];
                if($openid){
                    MsgService::sendRegFailMsg($openid, $pid,$beizhu);
                }
                return $this->returnResult(- 1, '审核成功');
            } else {
                return $this->returnResult(- 1, '审核失败');
            }
        }
    }

    /**
     * 后台代理关停
     */
    public function close() {
        $id = $this->request->param('id');
        $beizhu = $this->request->param('beizhu');
        $member = MemberModel::instance()->find($id);
        
        if (empty($member)) {
            return $this->returnResult(- 1, '数据不存在');
        }
        
        Log::write("delete member id:$id,remark:$beizhu");
        $data = [
            'id'=>$id,
            'status'=>4,
            'beizhu'=>$beizhu,
        ];
        $res = MemberModel::instance()->update($data);
        if ($res) {
            return $this->returnResult(- 1, '关闭成功');
        } else {
            return $this->returnResult(- 1, '关闭失败');
        }
    }

    public function update_agent() {
        $mid = $this->request->param('mid');
        $pid = $this->request->param('pid');
        $mebmer = MemberModel::instance()->find($mid); //
        $oldPidPath = $mebmer['pid_path'];

        $newPmember = MemberModel::instance()->find($pid);
        $pid_path = '';
        if ($newPmember) {
            if ($newPmember['pid_path']) {
                $pid_path = $newPmember['pid_path'] . ',' . $pid;
            } else {
                $pid_path = $pid;
            }
        }

        $data = [
            'id' => $mid,
            'fid' => $pid,
            'pid_path' => $pid_path,
            'updatetime' => Tools::getCurDate()
        ];

        $res = MemberModel::instance()->update($data);

        if ($oldPidPath || $pid_path) { // 原来有有父级
                                        // 如果有子集,就需要替换子集的pid_path
            $mids = MemberModel::instance()->getFMemberIdsByMid($mid);
            if ($mids) {
                $oldPids = explode(',', $oldPidPath);
                $oldPids = array_map('intval', $oldPids);
                $newPids = explode(',', $pid_path);
                if ($newPids) {
                    $newPids = array_map('intval', $newPids);
                }
                foreach ($mids as $id) {
                    $opidPath = MemberModel::instance()->where('id', $id)->value('pid_path');
                    $opidPathArray = array_map('intval', explode(',', $opidPath));
                    $afterPathArray = array_diff($opidPathArray, $oldPids); // 子集中移除原来父级中的pid_path
                    $afterNewPathArray = array_merge($newPids, $afterPathArray); // 把新的父级pid_path,放到子集的pid_path中
                    $afterNewPathArray = array_unique(array_filter($afterNewPathArray));
                    MemberModel::instance()->where('id', $id)->update([
                        'pid_path' => implode(',', $afterNewPathArray)
                    ]);
                }
            }
        }

        if ($res) {
            return json([
                "returnCode" => 1,
                "returnMsg" => "替换成功"
            ]);
        } else {
            return json([
                "returnCode" => - 2,
                "returnMsg" => "替换失败"
            ]);
        }
    }

    public function reset_pwd() {
        $mid = $this->request->param('mid');
        $member = MemberModel::instance()->where('id', $mid)->find();
        $phone = $member['tel'];
        $password = getPwd($phone);
        $data = [
            'id' => $mid,
            'password' => $password,
            'updatetime' => date('Y-m-d H:i:s')
        ];
        MemberModel::instance()->where('id', $mid)->update($data);
        return $this->returnResult(1);
    }

    // 代理树状图
    public function treeview() {
        return $this->fetch();
    }

    // 代理审核列表
    public function examine() {
        return $this->fetch();
    }

    // 代理详情
    public function detail() {
        $mid = $this->request->param('mid');
        $member = MemberModel::instance()->find($mid);
        $member['grade_name'] = WebUtil::getGradeName($member['grade']);

        $pname = '';

        if ($member['fid']) {
            $pname = MemberModel::instance()->where('id', $member['fid'])->value('name');
        }
        $member['pname'] = $pname;
        $where = [
            'mid' => $mid
        ];

        $recharge_money = 0; // 充值金额
        $recharge_count = 0; // 充值个数
        $withdraw_money = 0; // 提现金额
        $withdraw_count = 0; // 提现金额
        $reward_money = 0; // 奖励金额
        $reward_count = 0; //
        $order_count = 0;
        $order_account_money = 0; // 订单消耗充值金额
        $order_reward_account_money = 0; // 订单消耗奖励金额
        $received_addres_count = 0; // 收货地址
        $sender_addres_count = 0; // 发货地址

        $rechargeMap = RechargeModel::instance()->where($where)
            ->where('ifpass', 1)
            ->where('type', 1)
            ->group('mid')
            ->column('mid,sum(money) as money,count(0) count');
        if ($rechargeMap) {
            $recharge_money = $rechargeMap[$mid]['money'];
            $recharge_count = $rechargeMap[$mid]['count'];
        }
        $withdrawMap = RechargeModel::instance()->where($where)
            ->where('ifpass', 1)
            ->where('type', 2)
            ->group('mid')
            ->column('mid,sum(money) as money,count(0) count');
        if ($withdrawMap) {
            $withdraw_money = $withdrawMap[$mid]['money'];
            $withdraw_count = $withdrawMap[$mid]['count'];
        }

        $rewardMap = RewardModel::instance()->where($where)
            ->where('status', 1)
            ->group('mid')
            ->column('mid,sum(money) as money,count(0) count');
        if ($rewardMap) {
            $reward_money = $rewardMap[$mid]['money'];
            $reward_count = $rewardMap[$mid]['count'];
        }
        // 一级发货
        $orderMap = GoodsOrderModel::instance()->where($where)
            ->whereIn('ispay', [
            1,
            3,
            5
        ])
            ->group('mid')
            ->column('mid,sum(account) as money,sum(reward_account) as reward_money,count(0) count');
        if ($orderMap) {
            $order_account_money = $orderMap[$mid]['money'];
            $order_reward_account_money = $orderMap[$mid]['reward_money'];
            $order_count = $orderMap[$mid]['count'];
        }
        $addressMap = AddressModel::instance()->where($where)
            ->group('mid')
            ->column('mid,sum(type=1) as received_count,sum(type=2) as sender_count');
        if ($addressMap) {
            $received_addres_count = $addressMap[$mid]['received_count'];
            $sender_addres_count = $addressMap[$mid]['sender_count'];
        }
        $member['recharge_money'] = $recharge_money;
        $member['recharge_count'] = $recharge_count;
        $member['reward_money'] = $reward_money;
        $member['reward_count'] = $reward_count;
        $member['withdraw_money'] = $withdraw_money;
        $member['withdraw_count'] = $withdraw_count;
        $member['order_count'] = $order_count;
        $member['order_account_money'] = $order_account_money;
        $member['order_reward_account_money'] = $order_reward_account_money;
        $member['received_addres_count'] = $received_addres_count;
        $member['sender_addres_count'] = $sender_addres_count;

        $this->assign('item', $member);
        return $this->fetch();
    }

    public function address() {
        $mid = $this->request->param('mid', 0);
        $type = $this->request->param('type', 0);

        $this->assign('mid', $mid);
        $this->assign('type', $type);
        return $this->fetch();
    }

    public function address_rs() {
        $length = 10;
        $start = $this->request->param('start', 0);
        $draw = $this->request->param('draw', 1);
        $name = $this->request->param('name', '');
        $tel = $this->request->param('tel', '');
        $keywords = $this->request->param('keywords', '');
        $type = $this->request->param('type', '');
        $mid = $this->request->param('mid', 0);

        $where = [];
        if ($type != '') {
            $where['type'] = $type;
        }
        if ($mid) {
            $where['mid'] = $mid;
        }
        if ($keywords) {
            $mids = MemberModel::instance()->searchMidsByKeywords($keywords);
            $where['mid'] = [
                'in',
                $mids
            ];
        }
        if ($tel) {
            $where['tel'] = [
                'like',
                '%' . $tel . '%'
            ];
        }
        if ($name) {
            $where['name'] = [
                'like',
                "%$name%"
            ];
        }
        $items = AddressModel::instance()->where($where)
            ->limit($start, $length)
            ->order('id', 'desc')
            ->select();
        $count = AddressModel::instance()->where($where)->count();
        $items = collection($items)->toArray();
        $mids = ArrayUtil::getKeyValuesFromArray($items, 'mid');
        $memMap = MemberModel::instance()->whereIn('id', $mids)->column('id,name', 'id');
        $list = [];
        foreach ($items as $item) {
            $item['agent_name'] = $memMap[$item['mid']];
            $item['address'] = $item['addrvalue'] . ' ' . $item['addr'];
            $list[] = $item;
        }
        $data = array(
            "returnCode" => 1,
            "returnMsg" => "success!",
            'recordsTotal' => $count,
            'recordsFiltered' => $count,
            'draw' => $draw,
            'data' => $list
        );
        return json($data);
    }

    public function address_edit() {
        $id = $this->request->param('id');
        $address = AddressModel::instance()->find($id);
        $name = MemberModel::instance()->where('id', $address['mid'])->value('name');

        $this->assign('name', $name);
        $this->assign('item', $address);
        return $this->fetch();
    }

    public function address_edit_post() {
        $data = $this->request->param();
        $data['addtime'] = Tools::getCurDate();
        $data['updatetime'] = Tools::getCurDate();
        $res = AddressService::update($data);
        return $this->returnResult(1, '修改成功', [
            'id' => $res
        ]);
    }

    public function address_add() {
        $mid = $this->request->param('mid');
        $name = MemberModel::instance()->where('id', $mid)->value('name');
        $this->assign('mid', $mid);
        $this->assign('name', $name);
        return $this->fetch();
    }

    public function address_add_post() {
        $data = $this->request->param();
        $data['addtime'] = Tools::getCurDate();
        $data['updatetime'] = Tools::getCurDate();
        $res = AddressService::insert($data);
        return $this->returnResult(1, '添加成功', [
            'id' => $res
        ]);
    }
}
